package com.cvmars.jianyou.utils;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.cvmars.jianyou.api.api.Api;
import com.cvmars.jianyou.api.api.HttpUtils;
import com.cvmars.jianyou.api.api.SimpleSubscriber;
import com.cvmars.jianyou.api.model.HttpResult;
import com.cvmars.jianyou.api.model.QiNiuModel;
import com.cvmars.jianyou.config.MyConfig;
import com.cvmars.jianyou.model.ImageModel;
import com.cvmars.jianyou.model.UserModel;
import com.qiniu.android.common.FixedZone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * Created by hehaifeng on 2018/12/4.
 */

public class QiNiuUtils {

    UploadManager uploadManager;

    public static QiNiuUtils instance = new QiNiuUtils();

    public static QiNiuUtils getInstance() {

        return instance;
    }

    List<ImageModel> list = new ArrayList<>();

    private QiNiuUtils() {


        Configuration config = new Configuration.Builder()
                .chunkSize(512 * 1024)        // 分片上传时，每片的大小。 默认256K
                .putThreshhold(1024 * 1024)   // 启用分片上传阀值。默认512K
                .connectTimeout(10)           // 链接超时。默认10秒
                .useHttps(true)               // 是否使用https上传域名
                .responseTimeout(60)          // 服务器响应超时。默认60秒
                .zone(FixedZone.zone0)        // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
                .build();

// 重用uploadManager。一般地，只需要创建一个uploadManager对象
        uploadManager = new UploadManager(config);
    }


    int imgNum; //总图片数目

    int succNum; //成功的数目

    public void initImage(List<ImageModel> imageModels, Handler _handler) {
        list.clear();
        getQiuToken(imageModels, _handler);
    }


    private void getQiuToken(
            final List<ImageModel> imageModels, final Handler _handler) {


        HttpUtils.getInstance().toSubscribe(Api.getInstance()
                        .getQiNiuToken("", "image")
                , new SimpleSubscriber<HttpResult<QiNiuModel>>() {
                    @Override
                    protected void _onNext(HttpResult<QiNiuModel> o) {

                        if (imageModels != null && imageModels.size() > 0) {
                            imgNum = imageModels.size();
                            for (int i = 0; i < imageModels.size(); i++) {

                                uploadImage(imageModels.get(i), o.getData().token, imageModels.get(i).imgPath, _handler);
                            }
                        }
                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });


    }


    private void uploadImage(final ImageModel modelImg, String tokenQiNiu, String imgPath, final Handler _handler) {

        File data = new File(imgPath);

        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        String format1 = format.format(new Date());
        String prefix = imgPath.substring(imgPath.lastIndexOf(".") + 1);
        final String uploadKey = format1 + "/" + UtilHelper.generateShortUuid() + "." + prefix;
        LogUtils.d("uploadKey :" + uploadKey);
        LogUtils.d("tokenQiNiu :" + tokenQiNiu);


        uploadManager.put(data, uploadKey, tokenQiNiu,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        //res包含hash、key等信息，具体字段取决于上传策略的设置
                        if (info.isOK()) {
                            Log.i("qiniu", "Upload Success");
                        } else {
                            Log.i("qiniu", "Upload Fail");
                            //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                        }
                        Log.i("qiniu", key + ",\r\n " + info + ",\r\n " + res);

                        succNum++;

                        ImageModel model = new ImageModel();
                        model.uploadPath = uploadKey;
                        model.w = modelImg.w;
                        model.h = modelImg.h;

                        list.add(model);

                        if (succNum == imgNum) {

                            LogUtils.d("upload success :" + succNum);
                            succNum = 0;

                            Message message = Message.obtain();
                            message.obj = list;
                            _handler.sendMessage(message);
                        }
                    }
                }, null);

    }


}
